//
//  ASButton.m
//  AttendenceSys
//
//  Created by ld on 16/3/6.
//  Copyright © 2016年 窦芳俊. All rights reserved.
//

#import "ASButton.h"

@interface ASButton()
@property(nonatomic, strong)NSString *userid;
@property(nonatomic, copy)NSString*imageUrl;
@end

@implementation ASButton

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        //        self.exclusiveTouch = YES;//防止多个同时点击
        //        self.showsTouchWhenHighlighted  = YES;
        _headImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
        _headImageView.contentMode = UIViewContentModeScaleToFill;
        //        _headImageView.clipsToBounds = YES;
        [self addSubview:_headImageView];
        self.hidden = YES;
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame borderGap:(NSInteger)borderGap
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.exclusiveTouch = YES;//防止多个同时点击
        
        _borderGap = 0;// borderGap;
        //        CGFloat width = frame.size.width;
        //        CGFloat height = frame.size.height;
        //        CGFloat radius = (width>height)?height:width;
        //        self.layer.cornerRadius = radius*0.5;
        self.showsTouchWhenHighlighted  = YES;
        _headImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
        //        _headImageView = [[UIImageView alloc]initWithFrame:CGRectMake(_borderGap, _borderGap, radius-2*_borderGap, radius-2*_borderGap)];
        //        _headImageView.layer.cornerRadius = (radius*0.5-_borderGap);
        //        _headImageView.clipsToBounds = YES;
        [self addSubview:_headImageView];
        self.hidden = YES;
    }
    return self;
}

- (id)initQRWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.exclusiveTouch = YES;//防止多个同时点击
        
        //_borderGap = borderGap;
        CGFloat width = frame.size.width;
        CGFloat height = frame.size.height;
        CGFloat radius = (width>height)?height:width;
        self.layer.cornerRadius = radius*0.5;
        self.showsTouchWhenHighlighted  = YES;
        _headImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, width, height)];
        //        _headImageView.layer.cornerRadius = 5;
        //        _headImageView.clipsToBounds = YES;
        [self addSubview:_headImageView];
        self.hidden = YES;
    }
    return self;
}



-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

-(void)clearAllData
{
    self.image = nil;
    self.userid = nil;
    self.imageUrl = nil;
}

- (void)setNoMask:(BOOL)noMask
{
    _noMask = noMask;
    if (self.image != nil) {
        if (noMask) {
            _headImageView.image = _image;
        }
        else {
            //45是小头像的尺寸
            if (_headImageView.frame.size.width <= 45)
            {
                //_headImageView.image = [self maskImage:_image withMask: [RCSFontManage imageNamed:@"message_icon_headmask"]];
            }
            else
            {
                //_headImageView.image = [self maskImage:_image withMask: [RCSFontManage imageNamed:@"contect_icon_default_avatar_140x140"]];
            }
        }
    }
}

-(void)setImage:(UIImage *)image
{
    //    DebugLog("image.width = %f, image.height = %f",_headImageView.frame.size.width,_headImageView.frame.size.height);
    self.hidden = NO;
    if (self.noMask) {
        _headImageView.image = image;
    }
    else {
        //45是小头像的尺寸
        if (_headImageView.frame.size.width <= 45)
        {
            //_headImageView.image = [self maskImage:image withMask: [RCSFontManage imageNamed:@"message_icon_headmask"]];
        }
        else
        {
            //_headImageView.image = [self maskImage:image withMask: [RCSFontManage imageNamed:@"contect_icon_default_avatar_140x140"]];
        }
    }
    _image = image;
    [self setNeedsDisplay];
}

- (void)setImageWithURL:(NSString *)url placeholderImage:(UIImage *)placeholderImage
{
    [self clearAllData];
    if(url.length<=0)
    {
        [self setImage:placeholderImage forState:UIControlStateNormal] ;
        return;
    }
    
    NSString* fileName = [self fetchUserPicActivityName:url];
    UIImage* localImage = [self getLocalUserPicActivityImage:fileName];
    if (localImage) {
        [self setImage:localImage forState:UIControlStateNormal];
    }
    
    self.imageUrl = url;
    typeof(self) __weak weakSelf = self;
    NSURL *nsUrl= [NSURL URLWithString:url] ;
    if (nsUrl == NULL)
    {
        return;
    }
    
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [sessionManager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress){
//        if (progressBlock)
//        {
//            progressBlock(downloadProgress.completedUnitCount, downloadProgress.totalUnitCount);
//        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 主线程中执行
        NSData* imageData = (NSData *)responseObject;
        UIImage* iamge = [UIImage imageWithData:imageData];
        //iamge = [self maskImage:iamge withMask:[UIImage imageNamed:@"ic_add"]];
        
        if ([self.imageUrl isEqualToString:url]) {
            if (iamge) {
                NSString* fileName = [self fetchUserPicActivityName:url];
                NSString* path = [self fetchUserPicActivityFilePath:fileName];
                [kFileUtil saveToFile:imageData filePath:path atomically:YES];
                [weakSelf setImage:iamge forState:UIControlStateNormal];
            }
        }
        
        //[imageData writeToFile:savePath atomically:YES];
        
       // completionBlock(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //failure(error.description);
        //weakSelf.image = placeholderImage;
    }];
    
    
    
//    self.imageUrl = url;
//    typeof(self) __weak weakSelf = self;
//    [headMode commonImageDownloadWithUrl:url success:^(NSData *imageData,NSString* imageUrl) {
//        if ([self.imageUrl isEqualToString:imageUrl]) {
//            weakSelf.image = [UIImage imageWithData:imageData];
//        }
//        id<IRcSHeadImageMode> headImgMode = [[RcSModuleManager getModuleManager] getHeadImageInterface];
//        [headImgMode saveImageToFile:imageData fileName:fileName];
//    }];
}


-(UIImage*)maskImage:(UIImage *)image withMask:(UIImage *)maskImage
{
    CGImageRef maskRef = maskImage.CGImage;
    CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
                                        CGImageGetHeight(maskRef),
                                        CGImageGetBitsPerComponent(maskRef),
                                        CGImageGetBitsPerPixel(maskRef),
                                        CGImageGetBytesPerRow(maskRef),
                                        CGImageGetDataProvider(maskRef), NULL, false);
    
    CGImageRef masked = CGImageCreateWithMask([image CGImage], mask);
    UIImage* retImage = [UIImage imageWithCGImage:masked];
    CGImageRelease(mask);
    CGImageRelease(masked);
    
    return retImage;
    
}

- (NSString*)fetchUserPicActivityName:(NSString*)url
{
    NSString *tmp = [url copy];
    NSRange range = [tmp rangeOfString:@"/" options:NSBackwardsSearch];
    
    if (range.location == NSNotFound)
    {
        return nil;
    }
    
    return [tmp substringFromIndex:range.location];
}

- (NSString*)fetchUserPicActivityFilePath:(NSString*)picName
{
    NSString* path = [kFileUtil getAppDataPath];
    path = [path stringByAppendingPathComponent:@"Activity"];
    
    if (![kFileUtil isFileExist:path])
    {
        [kFileUtil createPath:path];
    }
    
    path = [path stringByAppendingPathComponent:picName];
    
    return path;
}

- (UIImage*)getLocalUserPicActivityImage:(NSString*)picName
{
    NSString* path = [kFileUtil getAppDataPath];
    path = [path stringByAppendingPathComponent:@"Activity"];
    path = [path stringByAppendingPathComponent:picName];
    UIImage* image = [UIImage imageWithContentsOfFile:path];
    return image;
}

@end
